package com.yjw.demo.netty.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 服务端
 *
 * @author yinjianwei
 * @date 2018/11/13
 */
public class Server {
    // 默认端口号
    private static final int DEFAULT_SERVER_PORT = 8888;
    // 服务端
    private static ServerSocket serverSocket;

    /**
     * 启动服务
     *
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        if (serverSocket != null) {
            return;
        }
        try {
            serverSocket = new ServerSocket(DEFAULT_SERVER_PORT);
            System.out.println("服务已启动，端口号：" + DEFAULT_SERVER_PORT);
            while (true) {
                Socket socket = serverSocket.accept();
                // 调用服务处理类处理
                Executor executor = getThreadPool(50, 10000);
                executor.execute(new ServerHandler(socket));
            }
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            serverSocket = null;
        }
    }

    /**
     * 获取线程池
     *
     * @param maxPoolSize
     * @param queueSize
     * @return
     */
    public static Executor getThreadPool(int maxPoolSize, int queueSize) {
        return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), maxPoolSize,
                120L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueSize));
    }
}